package com.example.Sao.Serivce;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.example.Sao.Custom.RxTimer;
import com.example.Sao.MyActivity.MyApplication;
import com.example.Sao.MyActivity.PCActivity;
import com.example.Sao.MyBean.Event;
import com.example.Sao.MyBean.PCInfoBean;
import com.example.Sao.MyFragment.WaitDialog;
import com.example.Sao.R;
import com.example.Sao.Tools.LogUtil;
import com.example.Sao.Tools.MyToast;
import com.example.Sao.Tools.ObjectBoxHelper;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.net.ServerSocket;
import java.net.Socket;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class PCService extends Service implements PConnectThread.Callback{
    private WaitDialog waitDialog,w1;
    private PCInfoBean infoBean;
    private ObjectBoxHelper objectBoxHelper;
    private PConnectThread pConnectThread = null;
    private PConnectThread connectthread;
    private final String TAG = "SocketService";
    private ServerSocket serverSocket  = null;
    private Socket socket = null;
    private MHandler mHandler;
    public PCService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //eventbus注册
        EventBus.getDefault().register(this);
        LogUtil.d(TAG, "服务开启");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int statrId) {
        LogUtil.d(TAG, "设置通知");
        //设置前台
        startForeground(1, set_notification());
        //绑定handler
        mHandler = new MHandler(this);
        //获取操作数据库对象
        objectBoxHelper = ObjectBoxHelper.getInstance();
//        //注册usb状态监听广播
//        BroadcastUtil.Register(this,new USBReceiver());

        //于PC通信线程
        pConnectThread =new PConnectThread(objectBoxHelper,this,this,mHandler);
        pConnectThread.start();
        return super.onStartCommand(intent, flags, statrId);
    }
    @Override
    public void callbcak(String msg) {
        Log.d(TAG,msg);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消eventbus注册
        EventBus.getDefault().unregister(this);
        //解除usb监听广播
//        BroadcastUtil.UnRegister(this);
        if (pConnectThread!=null){
            pConnectThread.close();
        }
    }

    /**
     * 普通事件处理
     */
    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void handleEvent (Event e){

    }

    /**
     * 自定义Handler子类防止内存泄漏
     */
    public   class MHandler extends Handler {
        private WeakReference<Service> reference;
        public MHandler(Service service) {
            // 使用WeakReference弱引用持有Activity实例
            reference = new WeakReference<Service>(service);
        }
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    waitDialog = new WaitDialog();
                    waitDialog.setTitle("正在自动上传盘点数据");
                    waitDialog.setmContext(PCService.this);
                    waitDialog.show(PCActivity.activty.getSupportFragmentManager(),"");
                    new RxTimer().timer2(1000, new RxTimer.IRxNext() {
                        @Override
                        public void doNext(long number, Disposable disposable) {
                            disposable.dispose();
                            waitDialog.dismiss();
                            Toast.makeText(PCService.this,"上传完成",Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
                case 2:
                    break;
                case 3:
                    if ("正在接受PC的盘点数据".equals(String.valueOf(msg.obj))){
                        w1 = new WaitDialog();
                        w1.setTitle("正在读取PC的盘点数据");
                        w1.setmContext(PCService.this);
                        w1.show(PCActivity.activty.getSupportFragmentManager(),"");
                        new RxTimer().interval(1, new RxTimer.IRxNext() {
                            @Override
                            public void doNext(long number, Disposable disposable) {
                                disposable.dispose();
                                w1.dismiss();
                                Toast.makeText(PCService.this,"数据保存成功",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    break;
                default:
            }
        }
    }

    /**
     * 设置前台弹窗
     */
    public Notification set_notification() {
        int pushId = 1;
        String PRIMARY_CHANNEL = "default";
        NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder;
        //判断是否是8.0Android.O
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel chan1 = new NotificationChannel(PRIMARY_CHANNEL,
                    "Primary Channel", NotificationManager.IMPORTANCE_DEFAULT);
            chan1.setLightColor(Color.GREEN);
            chan1.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
            mNotificationManager.createNotificationChannel(chan1);
            mBuilder = new NotificationCompat.Builder(getApplicationContext(), PRIMARY_CHANNEL);
        } else {
            mBuilder = new NotificationCompat.Builder(getApplicationContext());
        }
        Intent notificationIntent = new Intent(getApplicationContext(), PCActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0,
                notificationIntent, 0);
        mBuilder.setContentTitle("管理系统扫码设备")//设置通知栏标题
                .setContentText("盘点正在运行")//设置通知栏内容
                .setContentIntent(intent) //设置通知栏点击意模拟
//                .setNumber(++pushNum) //设置通知集合的数量
                .setTicker("管理系统扫码设备" + ":" + "正在盘点") //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setDefaults(Notification.DEFAULT_ALL)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                .setSmallIcon(R.mipmap.sao);//设置通知小ICON
        Notification notify = mBuilder.build();
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        mNotificationManager.notify(pushId, notify);
        return mBuilder.build();
    }

    /**
     * byte[] -->int byte[]转整形
     * @param res
     * @return
     */
    public static int byte2int(byte[] res) {
        // 一个byte数据左移24位变成0x??000000，再右移8位变成0x00??0000

        int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | 表示安位或
                | ((res[2] << 24) >>> 8) | (res[3] << 24);
        return targets;
    }
    /**
     * int --> byte[] 整形转byte[]
     * @param res
     * @return
     */
    public static byte[] int2byte(int res) {
        byte[] targets = new byte[4];

        targets[0] = (byte) (res & 0xff);// 最低位
        targets[1] = (byte) ((res >> 8) & 0xff);// 次低位
        targets[2] = (byte) ((res >> 16) & 0xff);// 次高位
        targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。
        return targets;
    }
}
